package com.capgemini.wechat.utils;

import com.capgemini.commons.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class WechatPostUtil {
    private static Logger logger = LoggerFactory.getLogger(WechatPostUtil.class);

    private static final String UTF_8 = "UTF-8";

    public String pushToWechatByUrl(String url, Object data)  {

        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-Type", "application/json");

        HttpEntity entity;
        String result = null;
        try{

            entity = new ByteArrayEntity(JsonUtil.getJson(data).getBytes(UTF_8));
            httppost.setEntity(entity);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity2 = response.getEntity();
                result = EntityUtils.toString(entity2);
                logger.info("result:" + result);

            } else {
                logger.error("request throw an error !>> {},{}" , response.getStatusLine().getStatusCode(), response.toString());

                Map map = new HashMap();

                map.put("status", response.getStatusLine().getStatusCode());
                map.put("data", response.toString());

                result = JsonUtil.getJson(map);
            }

            httpclient.close();
        }catch (Exception e){
            logger.error("", e);
        }


        return result;
    }

}
